import { UITransform, v3 } from "cc";
import { ecs } from "db://app-game/libs/ecs/ECS";
import { Circle } from "db://app-game/libs/math/auad-tree/Circle";
import QuadTreeUtil from "db://app-game/libs/math/auad-tree/QuadTreeUtil";
import { Rectangle } from "db://app-game/libs/math/auad-tree/Rectangle";
import { smc } from "../../../common/ecs/model/SingletonModuleComp";
import { StaticCreatureViewComp } from "../../static-creature/view/StaticCreatureViewComp";
import { Role } from "../Role";
import { RoleCollisionModelComp } from "../model/RoleCollisionModelComp";
import { RoleModelComp } from "../model/RoleModelComp";

/** 角色碰撞系统 */
@ecs.register("RoleCollision")
export class RoleCollisionSystem
  extends ecs.ComblockSystem
  implements ecs.ISystemUpdate
{
  filter(): ecs.IMatcher {
    return ecs.allOf(RoleModelComp, RoleCollisionModelComp);
  }
  update(role: Role, dt: number): void {
    // 检查 静态物体碰撞
    this.roleCollisionStaticCreature(role);
  }

  /** 角色碰撞 静态物体 */
  roleCollisionStaticCreature(role: Role) {
    if (!smc.level.map.staticCreature) return;
    const node = role.RoleModel.node;
    const roleUI = node.getComponent(UITransform);

    // 1.把位置更改到地图上面的位置
    const wPos = role.RoleModel.node
      .getComponent(UITransform)
      .convertToWorldSpaceAR(v3());
    const pos = smc.level.map.map
      .getComponent(UITransform)
      .convertToNodeSpaceAR(wPos);

    const params = {
      name: smc.level.map.staticCreature.name,
      circle: new Circle({
        x: pos.x,
        y: pos.y,
        xr: roleUI.width / 2,
        yr: roleUI.height / 2,
        data: { node },
      }),
    };
    const colliderList = smc.level.colliderList(params);

    const recentlyCollider = new Map();
    colliderList.forEach((obj) => {
      // 是否碰撞
      let isCollision = false;

      // 圆形和圆形
      if (obj instanceof Circle) {
        isCollision = QuadTreeUtil.ellipsesIntersecting(params.circle, obj);
      }
      // 圆形和矩形
      if (obj instanceof Rectangle) {
        QuadTreeUtil.ellipseAndRectIntersecting(params.circle, obj);
      }
      //  碰撞综合
      if (isCollision) {
        const staticCreature = obj.data.node.getComponent(
          StaticCreatureViewComp
        ).staticCreature;
        recentlyCollider.set(staticCreature.eid, staticCreature);
        if (
          !role.RoleCollisionModel.staticCreatureCollisionPools.has(
            staticCreature.eid
          )
        ) {
          staticCreature.setTransparent(true);
        }
      }
    });
    role.RoleCollisionModel.staticCreatureCollisionPools.forEach((item) => {
      if (!recentlyCollider.has(item.eid)) {
        item.setTransparent(false);
      }
    });
    role.RoleCollisionModel.staticCreatureCollisionPools = recentlyCollider;
  }
}
